#include <iostream>
#include "intSLList.hpp"
using namespace std;
IntSLList::~IntSLList(){
    for(IntSLLNode *p; !isEmpty();){
        p = head->next;
        delete head;
        head = p;
    }
}

void IntSLList::addToHead(int el){
    head = new IntSLLNode(el, head);
    if(tail == nullptr){
        tail = head;
    }
}

void IntSLList::addToTail(int el){
    if(tail != nullptr){
        tail->next = new IntSLLNode(el);
        tail = tail->next;
    }else
    {
        head = tail = new IntSLLNode(el);
    }
    
}

int* IntSLList::delFromHead(){
    int *el = nullptr;
    if(head == tail)
        if (head != nullptr){
            el = new int(head->info);
            delete head;
            head = tail = nullptr;
        }else
        {
            el = nullptr;
        }    
    else
    {
        el = new int(head->info);
        IntSLLNode *p = head;
        head =head->next;
        delete p;
    }
    return el;
}

int* IntSLList::delFromTail(){
    int* el = nullptr;
    if(head == tail){
        if (head != nullptr){
            el = new int(head->info);
            delete head;
            head = tail = nullptr;
        }else
        {
            el = nullptr;
        }    
    }else
    {
        IntSLLNode *p;
        for(p = head; p->next != tail; p = p->next);
        el = new int(tail->info);
        delete tail;
        tail = p;
        tail->next = nullptr;
    }
    return el;
}

void IntSLList::delNode(int el){
    if(head != nullptr){
        if(head == tail && el == tail->info){
            delete head;
            head = tail = nullptr;
        }else if(el == head->info){
            IntSLLNode *tmp = head;
            head = head->next;
            delete tmp;
        }else{
            IntSLLNode *pred, *tmp;
            for(pred = head, tmp = head->next;
                tmp != nullptr && !(tmp->info == el);
                pred = pred->next, tmp = tmp->next);
            if(tmp != nullptr){
                pred->next = tmp->next;
                if(tmp == tail){
                    tail = pred;
                }
                delete tmp;
            }
        }
    }
}

bool IntSLList::isInList(int el) const {
    IntSLLNode * tmp;
    for(tmp = head; tmp != nullptr && !(tmp->info == el); tmp = tmp->next);
    return tmp != nullptr;
}